<?php

namespace App\Services;

use App\Exceptions\CommonApiErrorException;
use App\Exceptions\CommonApiException;
use App\Models\Goods;
use App\Models\MarketActivityGoodsModel;
use App\Models\GoodsModel;
use App\Services\BaseService;
use Illuminate\Support\Facades\Log;

class MarketActivityService extends BaseService
{
    /**
     * @var static 单例模式
     */
    protected static $instance;

    /**
     * 保存活动页商品
     * @param $content string
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2023/11/20
     */
    public function saveGoodsFromContent($diyId, $content)
    {
        // 删除旧的
        MarketActivityGoodsModel::query()
            ->where('diy_id', $diyId)
            ->delete();

        if (empty($content)) {
            return false;
        }
        $contentArray = json_decode($content, true);
        if (empty($contentArray['pages']) || empty($contentArray['pages'][0]['elements'])) {
            return false;
        }

        $elements = $contentArray['pages'][0]['elements'];

        $goodsIdList = [];
        foreach ($elements as $element) {
            if ($element['elName'] === 'SeeGetData' && !empty($element['propsValue']['text_request_params']['value'])) {
                $value = json_decode($element['propsValue']['text_request_params']['value'], true);
                $goodsId = $value['id'];
                $goodsIdList[] = $goodsId;
            }
        }
        if (empty($goodsIdList)) {
            Log::notice('活动页暂无商品', ['location' => __METHOD__ . '[' . __LINE__ . ']']);
            return false;
        }
        $goodsIdList = array_unique($goodsIdList);

        // 检测：商品是否有不存在或被删除的
        $validGoodsIdList = Goods::query()
            ->where('is_delete', 0)
            ->whereIn('id', $goodsIdList)
            ->select('id')
            ->get()->unique('id')->pluck('id')->toArray();

        $invalidGoodsIdList = array_diff($goodsIdList, $validGoodsIdList);
        if ($invalidGoodsIdList) {
            throw new CommonApiException('存在不存在或被删除的商品');
        }

        // 插入新的
        $now = date('Y-m-d H:i:s', time());
        $saveDataBatch = [];
        foreach ($goodsIdList as $goodsId) {
            $saveDataBatch[] = [
                'diy_id' => $diyId,
                'goods_id' => $goodsId,
                'create_time' => $now,
            ];
        }

        $res = MarketActivityGoodsModel::query()->insert($saveDataBatch);
        if (!$res) {
            throw new CommonApiErrorException('保存活动页商品失败');
        }

        return true;
    }
}
